package sfeir.gwt.ergosum.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sfeir.gwt.ergosum.server.guice.GuiceServletContextListener;
import sfeir.gwt.ergosum.server.service.ProfileService;
import sfeir.gwt.ergosum.server.util.Pair;

import com.google.inject.Inject;
import com.google.inject.Injector;

@SuppressWarnings("serial")
public class PictureServlet extends HttpServlet {

    @Inject
    private ProfileService profileService;

    @Override
    public void init() throws ServletException {
        Injector injector = (Injector) getServletContext().getAttribute(GuiceServletContextListener.INJECTOR_NAME);
        injector.injectMembers(this);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getPathInfo();
        if (email != null && !email.equals("/"))
            email = email.substring(1);
        if (email.endsWith(".png"))
            email = email.substring(0, email.length() - 4);
        if (null != email) {
            Pair<byte[], String> picture = profileService.getProfilePicture(email);
//            resp.setContentType(picture.getSecond());
            resp.setContentType("image/png");
            resp.getOutputStream().write(picture.getFirst());
        }
    }
}
